import { defineStore } from 'pinia'
import {login, logout, userInfo} from '@/api/system'
import {setUserInfo, setToken, getToken, getUserInfo, removeAll} from '@/store/Store'

// 使用 Pinia 定义 Store
export const useSystemStore = defineStore('system', {
  // 状态定义
  state: () => ({
    token: getToken(),
    userInfo: getUserInfo()
  }),
  getters: {
    token: (state) => state.token,
    userInfo: (state) => state.userInfo,
  },
  // 动作定义
  actions: {
    changeUser(token) {
      // 直接修改状态（替代 commit('SET_TOKEN')）
      this.token = undefined
      this.userInfo = undefined
      this.token = token

      // 保留原存储逻辑（当 token 有效时更新存储）
      if (token) setToken(token)

      userInfo().then(ret => {
        this.userInfo = ret || {}
        if (ret) setUserInfo(ret)
      })

      uni.reLaunch({
        url: '/pages/index/home'
      })
    },

    // 使用 async/await 优化异步流程
    async login(params) {
      const ret = await login(params.params, params.config)
      this.token = ret.access_token
      if (ret.access_token) setToken(ret.access_token) // 保留原存储逻辑

      const user = await userInfo()
      this.userInfo = user || {}
      if (user) setUserInfo(user) // 保留原存储逻辑
    },

    async logout() {
      await logout()
      this.token = undefined
      this.userInfo = undefined
      removeAll()

      // 清除存储（原 mutations 中通过 undefined 触发清除）
      setToken(undefined)
      setUserInfo(undefined)

      uni.reLaunch({
        url: '/pages/index/login'
      })
    }
  }
})